<template>
  <el-card>
    <!-- 标题 + 新增 -->
    <template #header>
      <div class="flex-between">
        <span>结算类别管理</span>
        <el-button type="primary" @click="openDialog()">新增类别</el-button>
      </div>
    </template>

    <!-- 查询区 -->
    <el-form :inline="true" class="mb-3">
      <el-form-item label="关键字">
        <el-input
            v-model="query.keyword"
            placeholder="编码/名称"
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadData()">查询</el-button>
        <el-button @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表（已去掉 ID 列） -->
    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="settlecode" label="编码" width="120" />
      <el-table-column prop="settlename" label="名称" />
      <el-table-column prop="sequenceno" label="顺序" width="100" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="openDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="remove(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-3 text-right">
      <el-pagination
          :current-page="query.page"
          :page-size="query.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 50]"
          @current-change="page => { query.page = page; loadData() }"
          @size-change="size => { query.pageSize = size; loadData() }"
      />
    </div>
  </el-card>

  <!-- 新增/编辑对话框 -->
  <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="onDialogClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="编码" prop="settlecode">
        <el-input v-model="form.settlecode" />
      </el-form-item>
      <el-form-item label="名称" prop="settlename">
        <el-input v-model="form.settlename" />
      </el-form-item>
      <el-form-item label="顺序" prop="sequenceno">
        <el-input-number v-model="form.sequenceno" :min="1" style="width:100%" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="save()">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

// 接口返回的数据类型
interface SettleClass {
  id?: number
  settlecode: string
  settlename: string
  sequenceno: number
}

// 校验规则
const rules = {
  settlecode:   [{ required: true, message: '请输入编码', trigger: 'blur' }],
  settlename:   [{ required: true, message: '请输入名称', trigger: 'blur' }],
  sequenceno:   [{ required: true, type: 'number', message: '请输入顺序', trigger: 'change' }],
}

// 分页查询参数
const query = reactive({
  page:      1,
  pageSize: 10,
  keyword:  ''
})

// 列表数据 & 总数
const tableData = ref<SettleClass[]>([])
const total     = ref(0)

// 对话框 & 表单模型
const dialogVisible = ref(false)
const dialogTitle   = ref('新增类别')
const form = reactive<SettleClass>({
  id:           undefined,
  settlecode:   '',
  settlename:   '',
  sequenceno:   1
})
const formRef = ref<any>()

// 重置查询
function reset() {
  query.keyword  = ''
  query.page     = 1
  query.pageSize = 10
  loadData()
}

// 拉取列表
async function loadData() {
  try {
    const res = await axios.get('/api/master/settle/list', {
      params: { keyword: query.keyword }
    })
    const data: SettleClass[] = res.data

    // 本地过滤（后端若支持可省略）
    const filtered = data.filter(item =>
        !query.keyword ||
        item.settlecode.includes(query.keyword) ||
        item.settlename.includes(query.keyword)
    )

    total.value = filtered.length
    const start = (query.page - 1) * query.pageSize
    tableData.value = filtered.slice(start, start + query.pageSize)
  } catch {
    ElMessage.error('获取列表失败')
  }
}

// 打开新增/编辑对话框
function openDialog(row?: SettleClass) {
  if (row && row.id != null) {
    dialogTitle.value = '编辑类别'
    Object.assign(form, row)
  } else {
    dialogTitle.value = '新增类别'
    Object.assign(form, { id: undefined, settlecode: '', settlename: '', sequenceno: 1 })
  }
  dialogVisible.value = true
}

// 关闭时清空校验
function onDialogClose() {
  formRef.value?.clearValidate()
}

// 保存（新增或更新）
async function save() {
  await formRef.value.validate()
  try {
    await axios.post('/api/master/settle/saveOrUpdate', form)
    ElMessage.success(form.id != null ? '更新成功' : '新增成功')
    dialogVisible.value = false
    query.page = 1
    loadData()
  } catch {
    ElMessage.error('保存失败')
  }
}

// 删除
async function remove(row: SettleClass) {
  try {
    await ElMessageBox.confirm('确认删除该类别吗？', '警告', { type: 'warning' })
    await axios.delete(`/api/master/settle/deleteById/${row.id}`)
    ElMessage.success('删除成功')
    if (tableData.value.length === 1 && query.page > 1) {
      query.page--
    }
    loadData()
  } catch {
    // 取消或失败时不额外提示
  }
}

// 首次加载
onMounted(loadData)
</script>

<style scoped>
.flex-between { display: flex; justify-content: space-between; align-items: center; }
.mb-3          { margin-bottom: 12px; }
.mt-3          { margin-top: 12px; }
.text-right    { text-align: right; }
</style>
